package com.treeroot.treenet.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * Create By TreeRoot
 * Create Time: 2023/12/18 03:37
 * Class Name: WsUtils
 * Description:
 * Websocket工具
 * @author TreeRoot
 */
public class WsUtils {

    /**
     * 提取websocket的key
     *
     * @param httpRequest http请求
     * @return Sec-WebSocket-Key
     */
    public static String extractWebSocketKey(String httpRequest) {
        String keyHeader = "Sec-WebSocket-Key:";
        int start = httpRequest.indexOf(keyHeader) + keyHeader.length();
        int end = httpRequest.indexOf("\r\n", start);
        return httpRequest.substring(start, end).trim();
    }

    /**
     * 计算websocket的accept
     *
     * @param webSocketKey Sec-WebSocket-Key
     * @return Sec-WebSocket-Accept
     */
    public static String calculateWebSocketAccept(String webSocketKey) {
        byte[] sha1 = null;
        String magicString = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        String concatenated = webSocketKey + magicString;
        try {
            sha1 = MessageDigest.getInstance("SHA-1").digest(concatenated.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            System.out.println(e);
        }
        return Base64.getEncoder().encodeToString(sha1);
    }
}
